<script setup>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'

</script>

<script>
import {gen, gen2} from "@/api/ollama-api.js";

export default {
  data() {
    return {
      myText: '',
      aiResponse: ''
    }
  },
  methods: {

    setMyText(text) {
      if (text) {
        this.aiResponse += text;
      }
    },

    async handleInput() {
      this.aiResponse = '';
      const decoder = new TextDecoder('utf-8');
      let ai = await gen2({
        model: "Yi",
        prompt: this.myText
      })
      //     .then(response => {
      //   const reader = response.body.getReader();
      //   return reader.read().then(function process({done, value}) {
      //     if (done) {
      //       return;
      //     }
      //     let valueStr = decoder.decode(value);
      //     console.log('decoder', valueStr)
      //
      //     return reader.read().then(process);
      //   });
      // }).catch(console.error);
      // 获取读取可读流
      let reader = ai.body.getReader();
      while (1) {
        let res = await reader.read();
        if (res.done) {
          console.log('break')
          break;
        }
        let str = decoder.decode(res.value);
        console.log('decoder', str)
        let lineArr = str.split("\n");
        console.log(lineArr)
        if (lineArr.length > 2) {
          console.log("--------------------------------------------")
        }
        for (let i = 0; i < lineArr.length; i++) {
          let line = lineArr[i];
          if (!line) {
            continue
          }
          const data = JSON.parse(line);
          this.setMyText(data.response)
        }
      }
    }
  }

}
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125"/>

    <div class="wrapper">
      <HelloWorld msg="You did it!"/>
    </div>
  </header>

  <main>
    <TheWelcome/>
    <p>{{ myText }}</p>
    <p>{{ aiResponse }}</p>
    <InputText type="text" v-model="myText"/>
    <Button severity="success" @click="handleInput">哈哈哈</Button>
  </main>
</template>

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>
